package br.com.yk.client;

import java.util.List;

import br.com.siam.pojo.Device;
import br.com.yk.client.services.DeviceService;
import br.com.yk.client.services.UserService;
import br.com.yk.client.ui.LoginForm;
import br.com.yk.client.ui.MainForm;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.HTMLPanel;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.Viewport;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.TextField;
import com.gwtext.client.widgets.menu.Menu;
import com.gwtext.client.widgets.menu.MenuItem;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class EstufaWEB implements EntryPoint {
	
	private final Panel centerPanelTwo = new HTMLPanel();

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final LoginForm loginForm = new LoginForm();
		
		loginForm.getBtLogin().addListener( new ButtonListenerAdapter() {
	         public void onClick(Button button, EventObject e ) {
	        	UserService.Util.getInstance().isValidLogin(loginForm.getTxtLoginName().getText(), loginForm.getTxtPassword().getText(), new AsyncCallback<Boolean>() {
					
					@Override
					public void onSuccess(Boolean result) {
						if (result) {
							MessageBox.alert("Login", "Login válido");
							loginForm.hide();
							new MainForm();
						}
						else {
							MessageBox.alert("Login", "Login inválido. Tente novamente.");
						}
					}
					
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}
				});
//	            Map loginData = getUserData( formPanel.getForm() );
//	            loginService.userIsValid( loginData, callback );
	         }
	      });
		new Viewport(loginForm);
		
		
//	       Panel panel = new Panel();  
//	        panel.setBorder(false);  
//	        panel.setPaddings(0);  
//	        panel.setLayout(new FitLayout());  
//	  
//	        Panel borderPanel = new Panel();  
//	        borderPanel.setLayout(new BorderLayout());  
//	  
//	        //add north panel  
//	        //raw html  
//	        BoxComponent northPanel = new BoxComponent();  
//	        northPanel.setEl(new HTML("<p>north - generally for menus, toolbars" +  
//	                " and/or advertisements</p>").getElement());  
//	        northPanel.setHeight(32);
//	        Toolbar toolbar = createToolbar();
//	        borderPanel.add(toolbar, new BorderLayoutData(RegionPosition.NORTH));  
//	  
//	        //add south panel  
//	        Panel southPanel = new HTMLPanel("<p>south - generally for informational stuff," +  
//	                " also could be for status bar</p>");  
//	        southPanel.setHeight(100);  
//	        southPanel.setCollapsible(true);  
//	        southPanel.setTitle("South");  
//	  
//	        BorderLayoutData southData = new BorderLayoutData(RegionPosition.SOUTH);  
//	        southData.setMinSize(100);  
//	        southData.setMaxSize(200);  
//	        southData.setMargins(new Margins(0, 0, 0, 0));  
//	        southData.setSplit(true);  
//	        borderPanel.add(southPanel, southData);  
//	  
//	        //add east panel  
//	        Panel eastPanel = new Panel();  
//	        eastPanel.setTitle("East Side");  
//	        eastPanel.setCollapsible(true);  
//	        eastPanel.setWidth(225);  
//	        eastPanel.setLayout(new FitLayout());  
//	  
//	        BorderLayoutData eastData = new BorderLayoutData(RegionPosition.EAST);  
//	        eastData.setSplit(true);  
//	        eastData.setMinSize(175);  
//	        eastData.setMaxSize(400);  
//	        eastData.setMargins(new Margins(0, 0, 5, 0));  
//	  
//	        borderPanel.add(eastPanel, eastData);  
//	  
//	        TabPanel tabPanel = new TabPanel();  
//	        tabPanel.setBorder(false);  
//	        tabPanel.setActiveTab(1);  
//	  
//	        Panel tabOne = new Panel();  
//	        tabOne.setHtml("<p>A TabPanel component can be a region.</p>");  
//	        tabOne.setTitle("A Tab");  
//	        tabOne.setAutoScroll(true);  
//	        tabPanel.add(tabOne);  
//	  
//	        PropertyGridPanel propertyGrid = new PropertyGridPanel();  
//	        propertyGrid.setTitle("Property Grid");  
//	  
//	        Map source = new HashMap();  
//	        source.put("(name)", "Properties Grid");  
//	        source.put("grouping", Boolean.FALSE);  
//	        source.put("autoFitColumns", Boolean.TRUE);  
//	        source.put("productionQuality", Boolean.FALSE);  
//	        source.put("created", new Date());  
//	        source.put("tested", Boolean.FALSE);  
//	        source.put("version", new Float(0.1f));  
//	        source.put("borderWidth", new Integer(1));  
//	  
//	        propertyGrid.setSource(source);  
//	  
//	        tabPanel.add(propertyGrid);  
//	        eastPanel.add(tabPanel);  
//	  
//	        final AccordionLayout accordion = new AccordionLayout(true);  
//	  
//	        Panel westPanel = new Panel();  
//	        westPanel.setTitle("West");  
//	        westPanel.setCollapsible(true);  
//	        westPanel.setWidth(200);  
//	        westPanel.setLayout(accordion);  
//	  
//	        Panel navPanel = new Panel();  
//	        navPanel.setHtml("<p>Hi. I'm the west panel.</p>");  
//	        navPanel.setTitle("Navigation");  
//	        navPanel.setBorder(false);  
//	        navPanel.setIconCls("forlder-icon");  
//	        westPanel.add(navPanel);  
//	  
//	        Panel settingsPanel = new Panel();  
//	        settingsPanel.setHtml("<p>Some settings in here.</p>");  
//	        settingsPanel.setTitle("Settings");  
//	        settingsPanel.setBorder(false);  
//	        settingsPanel.setIconCls("settings-icon");  
//	        westPanel.add(settingsPanel);  
//	  
//	        BorderLayoutData westData = new BorderLayoutData(RegionPosition.WEST);  
//	        westData.setSplit(true);  
//	        westData.setMinSize(175);  
//	        westData.setMaxSize(400);  
//	        westData.setMargins(new Margins(0, 5, 0, 0));  
//	  
//	        borderPanel.add(westPanel, westData);  
//	  
//	        TabPanel centerPanel = new TabPanel();  
//	        centerPanel.setDeferredRender(false);  
//	        centerPanel.setActiveTab(0);  
//	  
//	        Panel centerPanelOne = new HTMLPanel();  
//	        centerPanelOne.setHtml(  
//	                "<p><b>Done reading me? Close me by clicking the X in the top right corner.</b></p>\n" +  
//	                        "<p>" + getShortBogusMarkup() + "</p>\n" +  
//	                        "<p>" + getShortBogusMarkup() + "</p>\n" +  
//	                        "<p>" + getShortBogusMarkup() + "</p>\n"  
//	        );  
//	        centerPanelOne.setTitle("Close Me");  
//	        centerPanelOne.setAutoScroll(true);  
//	        centerPanelOne.setClosable(true);  
//	  
//	        centerPanel.add(centerPanelOne);  
//	  
//	        //centerPanelTwo = new HTMLPanel();  
//	        centerPanelTwo.setHtml(  
//	                "<p>My closable attribute is set to false so you can't close me. The other center panels " +  
//	                        "can be closed.</p>\n" +  
//	                        "<p>The center panel automatically grows to fit the remaining space in the container " +  
//	                        "that isn't taken up by the border regions.</p>\n" +  
//	                        "<hr>\n" +  
//	                        "<p>" + getShortBogusMarkup() + "</p>\n" +  
//	                        "<p>" + getShortBogusMarkup() + "</p>\n" +  
//	                        "<p>" + getShortBogusMarkup() + "</p>\n" +  
//	                        "<p>" + getShortBogusMarkup() + "</p>\n");  
//	        centerPanelTwo.setTitle("Center Panel");  
//	        centerPanelTwo.setAutoScroll(true);  
//	  
//	        centerPanel.add(centerPanelTwo);  
//	        borderPanel.add(centerPanel, new BorderLayoutData(RegionPosition.CENTER));  
//	  
//	        panel.add(borderPanel);  
//	  
//	        new Viewport(panel);  
	    }  
	  
	        
//		final Button sendButton = new Button("Send");
//		final TextBox nameField = new TextBox();
//		nameField.setText("GWT User");
//		final Label errorLabel = new Label();
//
//		// We can add style names to widgets
//		sendButton.addStyleName("sendButton");
//
//		// Add the nameField and sendButton to the RootPanel
//		// Use RootPanel.get() to get the entire body element
//		RootPanel rootPanel = RootPanel.get("nameFieldContainer");
//		rootPanel.add(nameField);
//		RootPanel.get("sendButtonContainer").add(sendButton);
//		RootPanel.get("errorLabelContainer").add(errorLabel);
//
//		// Focus the cursor on the name field when the app loads
//		nameField.setFocus(true);
//		
//		
//		// Create the popup dialog box
//		final DialogBox dialogBox = new DialogBox();
//		dialogBox.setText("Remote Procedure Call");
//		dialogBox.setAnimationEnabled(true);
//		final Button closeButton = new Button("Close");
//		// We can set the id of a widget by accessing its Element
//		closeButton.getElement().setId("closeButton");
//		final Label textToServerLabel = new Label();
//		final HTML serverResponseLabel = new HTML();
//		VerticalPanel dialogVPanel = new VerticalPanel();
//		dialogVPanel.addStyleName("dialogVPanel");
//		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
//		dialogVPanel.add(textToServerLabel);
//		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
//		dialogVPanel.add(serverResponseLabel);
//		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
//		dialogVPanel.add(closeButton);
//		dialogBox.setWidget(dialogVPanel);
//		
//		Button btnNewButton = new Button("New button");
//		btnNewButton.addClickHandler(new ClickHandler() {
//			public void onClick(ClickEvent event) {
//				DeviceService.Util.getInstance().createDevice(nameField.getText(), new AsyncCallback<Device>() {
//					
//					@Override
//					public void onSuccess(Device result) {
//						dialogBox.setText("Device " + result.getName());
//						serverResponseLabel.removeStyleName("serverResponseLabelError");
//						serverResponseLabel.setHTML("id: " + result.getId() + " - " + result.getName());
//						dialogBox.center();
//						closeButton.setFocus(true);
//					}
//					
//					@Override
//					public void onFailure(Throwable caught) {
//						dialogBox.setText("Erro no Device ");
//						serverResponseLabel.setHTML("Erro: " + caught.getMessage());
//						dialogBox.center();
//						closeButton.setFocus(true);
//					}
//				});
//			}
//		});
//		rootPanel.add(btnNewButton, 62, 169);
//		
//		Button btnNewButton2 = new Button("New button2");
//		btnNewButton2.addClickHandler(new ClickHandler() {
//			public void onClick(ClickEvent event) {
//				DeviceService.Util.getInstance().findDevices(new AsyncCallback<List<Device>>() {
//					
//					@Override
//					public void onSuccess(List<Device> result) {
//						String message = "";
//						for (Device device : result) {
//							message += "id: " + device.getId() + " - name: " + device.getName() + "<br>";
//						}
//						
//						
//						dialogBox.setText("Device list");
//						serverResponseLabel.removeStyleName("serverResponseLabelError");
//						serverResponseLabel.setHTML(message);
//						dialogBox.center();
//						closeButton.setFocus(true);
//						
//						if (Window.confirm("Esta vendo isso?")) {
//							Window.alert("Sim");
//						}
//					}
//					
//					@Override
//					public void onFailure(Throwable caught) {
//						// TODO Auto-generated method stub
//						
//					}
//				});
//			}
//		});
//		rootPanel.add(btnNewButton2, 162, 269);
//		
//		nameField.selectAll();
//
//
//		// Add a handler to close the DialogBox
//		closeButton.addClickHandler(new ClickHandler() {
//			public void onClick(ClickEvent event) {
//				dialogBox.hide();
//				sendButton.setEnabled(true);
//				sendButton.setFocus(true);
//			}
//		});
//
//		// Create a handler for the sendButton and nameField
//		class MyHandler implements ClickHandler, KeyUpHandler {
//			/**
//			 * Fired when the user clicks on the sendButton.
//			 */
//			public void onClick(ClickEvent event) {
//				sendNameToServer();
//			}
//
//			/**
//			 * Fired when the user types in the nameField.
//			 */
//			public void onKeyUp(KeyUpEvent event) {
//				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
//					sendNameToServer();
//				}
//			}
//
//			/**
//			 * Send the name from the nameField to the server and wait for a response.
//			 */
//			private void sendNameToServer() {
//				// First, we validate the input.
//				errorLabel.setText("");
//				String textToServer = nameField.getText();
//				if (!FieldVerifier.isValidName(textToServer)) {
//					errorLabel.setText("Please enter at least four characters");
//					return;
//				}
//
//				// Then, we send the input to the server.
//				sendButton.setEnabled(false);
//				textToServerLabel.setText(textToServer);
//				serverResponseLabel.setText("");
//			}
//		}
//
//		// Add a handler to send the name to the server
//		MyHandler handler = new MyHandler();
//		sendButton.addClickHandler(handler);
//		nameField.addKeyUpHandler(handler);
    private static String getShortBogusMarkup() {  
        return "<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. " +  
                "Sed metus nibh, sodales a, porta at, vulputate eget, dui.  " +  
                "In pellentesque nisl non sem. Suspendisse nunc sem, pretium eget, " +  
                "cursus a, fringilla vel, urna.";  
    }  
    
    private Toolbar createToolbar() {
    	 //create a toolbar and various menu items  
        Toolbar toolbar = new Toolbar();  
  
        Menu menu = new Menu();  
        menu.setShadow(true);  
        menu.setMinWidth(10);  
  
        MenuItem miDevice = new MenuItem();
        miDevice.setText("Dispositivos");
        menu.addItem(miDevice);  
  
        menu.addSeparator();  

        MenuItem miClose = new MenuItem();
        miClose.setText("Sair");
        menu.addItem(miClose);  
        
        ToolbarButton menuButton = new ToolbarButton("Arquivo");  
        menuButton.setMenu(menu);  
        menuButton.setIconCls("bmenu");  
        toolbar.addButton(menuButton);
        
        toolbar.addSeparator();  
  
        ToolbarButton iconDevice = new ToolbarButton();  
        iconDevice.setIcon("images/add-feed.gif");  
        iconDevice.setCls("x-btn-icon");  
        iconDevice.setTooltip("<b>Devices</b><br/>Lista dispositivos");
        iconDevice.addListener(new ButtonListenerAdapter() {
        	@Override
        	public void onClick(Button button, EventObject e) {
				DeviceService.Util.getInstance().findDevices(new AsyncCallback<List<Device>>() {
					
					@Override
					public void onSuccess(List<Device> result) {
						String message = "";
						for (Device device : result) {
							message += "id: " + device.getId() + " - name: " + device.getName() + "<br>";
						}
						centerPanelTwo.setHtml(message);
					}
					
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}
				});        		
        	}
        });
        toolbar.addButton(iconDevice);
        
        toolbar.addSeparator();  

        // user name
        TextField txtUserName = new TextField();  
        toolbar.addField(txtUserName);
        
        // password
        TextField txtPassword = new TextField();  
        toolbar.addField(txtPassword);
        
        return toolbar;
    }
}
